package cn.org.timespace.ons.dao.base.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import cn.org.timespace.ons.action.base.MachinesModel;
import cn.org.timespace.ons.dao.TSBaseDAO;
import cn.org.timespace.ons.dao.base.MachinesDao;
import cn.org.timespace.ons.util.pager.Pager;
import cn.org.timespace.ons.vo.base.Machines;
import cn.org.timespace.ons.vo.base.Options;
import cn.org.timespace.ons.vo.base.UserMachineType;

public class MachinesDaoImpl extends TSBaseDAO implements MachinesDao {

	@Override
	public List<Machines> findByCondition(MachinesModel model) {
		// TODO Auto-generated method stub
		
		StringBuffer queryString = new StringBuffer("from Machines m where 1=1");
		if(!StringUtils.isEmpty(model.getCompCode())){
			queryString.append("and m.compCode like '%" + model.getCompCode() + "'%" );
		}
		if(!StringUtils.isEmpty(model.getMachinesID())){
			queryString.append("and m.machinesID = '" + model.getMachinesID() + "'" );
		}
		if(!StringUtils.isEmpty(model.getBatch())){
			queryString.append("and m.batch = '" + model.getBatch() + "'" );
		}
		if(!StringUtils.isEmpty(model.getTheIdMachine())){
			queryString.append("and m.theIdMachine = '" + model.getTheIdMachine() + "'" );
		}
		
		queryString.append(" order by m.mid desc");
		
		
		return getHibernateTemplate().find(queryString.toString());
	}

	@Override
	public List<Object> findByCondition(MachinesModel model, Pager p) {
		log.debug("finding all EfUserLoginLog instances");
		Session session = null;
		SQLQuery query = null;
		try{
			StringBuffer queryString = new StringBuffer("select u.name,m.compCode,m.deviceCode,m.deviceRandom,m.name,m.status,m.address,m.remark,m.mid,m.type,m.batch,mo.ipAddress " +
					"from usermachinetype u,machines m left join machinesmom mm  on m.mid=mm.msid   left join  mom mo  on mm.momid=mo.momid " +
					"where 1=1 and m.theIdMachine=u.theIdMachine  ");
			//Machines
			//select o.name,m.compCode,m.compRandom,m.deviceCode,m.deviceRandom,m.name,m.status,m.address,m.remark,m.momid from Options o,Mom m where 1=1 and m.type=o.theId
			if(!StringUtils.isEmpty(model.getCompCode())){
				queryString.append(" and m.compCode = '" + model.getCompCode().trim() + "'" );
			}
			
			
			//类型条件
			if(!StringUtils.isEmpty(model.getTheIdMachine())){
				queryString.append(" and m.theIdMachine = '" + model.getTheIdMachine().trim() + "'" );
			}
			
			//设备名称条件
			if(!StringUtils.isEmpty(model.getUserName())){
				queryString.append(" and m.userName like '%" + model.getUserName() + "%'" );
			}
			
			
			//批次
			if(!StringUtils.isEmpty(model.getBatch())){
				queryString.append(" and m.batch like '%" + model.getBatch() + "%'" );
			}
			queryString.append(" and m.status = '"+model.getStatus()+"'");
			queryString.append(" order by m.createTime asc");
			session = getSessionFactory().openSession();
			query = session.createSQLQuery(queryString.toString());
			
			
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			
			setQueryPager(query, p);
			//resList.add(query.list());
			
			List list = new ArrayList();
			for(int i = 0;i < query.list().size();i++){
				Object[] obj=(Object[])query.list().get(i);
				
				Machines machines = new Machines();
				machines.setTheIdMachine(obj[0].toString());
				machines.setCompCode(obj[1].toString());
				machines.setDeviceCode(obj[2].toString());
				machines.setDeviceRandom((obj[3].toString()));
				machines.setName((obj[4].toString()));
				machines.setStatus(Integer.parseInt(obj[5].toString()));
				machines.setAddress(obj[6].toString());
				//machines.setRemark(obj[7].toString());
				machines.setMid(((obj[8].toString())));
				machines.setType(obj[9].toString());
				machines.setBatch(String.valueOf(obj[10]));
				machines.setUserName(obj[11]==null?"":obj[11].toString());
				list.add(machines);
			}
			resList.add(list);
			return resList;
		}catch(RuntimeException re){
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(Machines persistentInstance) {
		// TODO Auto-generated method stub
		log.debug("deleting Machines Instance");
		try{
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		}catch(RuntimeException re){
			log.debug("delete fail",re);
			throw re;
		}
	}

	@Override
	public Machines findById(String mid) {
		// TODO Auto-generated method stub
		log.debug("getting Machines instance with id: " +mid);
		try{
			Machines instance = (Machines)getHibernateTemplate().get(
					"cn.org.timespace.ons.vo.base.Machines", mid);
			return instance;
		}catch(RuntimeException re){
			log.debug("get fail",re);
			throw re;
		}
	}

	@Override
	public void save(Machines transientInstance) {
		// TODO Auto-generated method stub
		log.debug("saving Machines Instance");
		try{
			getHibernateTemplate().save(transientInstance);
			log.debug("saving successful");
		}catch(RuntimeException re){
			log.debug("saving fail",re);
			throw re;
		}
		
	}

	@Override
	public void update(Machines instance) {
		
		try{
			getHibernateTemplate().update(instance);
			
		}catch(RuntimeException re){
			log.error("update failed!",re);
			throw re;
		}
		
	}

	@Override
	public List<Object> findByCondition(Pager p) {
	log.debug("finding all EfUserLoginLog instances");
		
		Session session = null;
		Query query = null;
		try {
			StringBuffer queryString = new StringBuffer("from Machines m ");
			
			queryString.append(" order by m.mid desc ");
			
			session = getSessionFactory().openSession();
			query = session.createQuery(queryString.toString());
			List<Object> resList = new ArrayList();
			resList.add(query.list().size());
			setQueryPager(query, p);
			resList.add(query.list());
			return resList;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}finally{
			closeSessionAndQuery(session, query);
		}
	}

	@Override
	public List<Options> findByCode(String code) {
		log.debug("finding all findByCode instances");
	    String hql = "from Options o where code='"+code+"'";
	    return (List<Options>) this.getHibernateTemplate().find(hql);
	}

	@Override
	public List<UserMachineType> doListMachineTypeName(String userName) {
		// TODO Auto-generated method stub
		log.debug("finding all instances");
	    String hql = "from UserMachineType where userId='"+userName+"'";
	    return (List<UserMachineType>) this.getHibernateTemplate().find(hql);
	}

	@Override
	public Machines findByCondition(String compCode, 
			String deviceCode, String deviceRandom) {
		// TODO Auto-generated method stub
		StringBuffer queryString = new StringBuffer("from Machines m where 1=1");
		
			queryString.append(" and m.compCode ='" +compCode+ "'");
		
			queryString.append(" and m.deviceCode ='" +deviceCode+ "'");
		
//			queryString.append(" and m.deviceRandom ='" +deviceRandom+ "'");
		
		
		List<Machines> resList = getHibernateTemplate().find(queryString.toString());
		if(resList != null && resList.size() == 1){
			return resList.get(0);
		}
		return null;
	}
	
	@Override
	public Machines findByCondition(String deviceCodes) {
		StringBuffer queryString = new StringBuffer("from Machines m where status=1");
			queryString.append(" and m.machinesID = '" +deviceCodes+ "'");
		List<Machines> resList = getHibernateTemplate().find(queryString.toString());
		if(resList != null && resList.size() == 1){
			return resList.get(0);
		}
		return null;
	}
	
	@Override
	public void insertBatch(List<Machines> list){
		for(Machines machines:list){
			this.save(machines);
		}
	}
	
	//批次列表
	public List<Object> findByBatch() {
		log.debug("finding all findByBatch instances");
		Session session = null;
		Query query = null;
		StringBuffer queryString = new StringBuffer("select distinct batch from Machines m ");
	    session = getSessionFactory().openSession();
		query = session.createQuery(queryString.toString());
		
		return query.list();
	}
}
